var flag = false

Page({
  data: {
    settingsArray: ['起床时间','出门时间','到家时间','睡觉时间'],
    timeArray: ['06:00','08:00','18:00','23:00'],
    checked: false
  },

  onLoad: function(e) {
    flag = false

    wx.getStorage({
      key: 'timeArray',
      success: res => {
        this.setData({
          timeArray: res.data
        })
      }
    })

    wx.getStorage({
      key: 'checked',
      success: res => {
        this.setData({
          checked: res.data
        })
      }
    })
  },

  onUnload: function(e) {
    if(flag) return

    wx.showModal({
      cancelColor: 'cancelColor',
      content: '是否保存刚才的设置',
      success: res => {
        if(!res.cancel) {
          this.save()
        }
      }
    })
  },

  timeChange: function(e) {
    let index = e.currentTarget.dataset.index
    console.log(index)
    this.setData({
      ['timeArray['+ index +']']: e.detail.value
    })
  },

  save: function(e) {
    wx.setStorage({
      data: this.data.timeArray,
      key: 'timeArray',
    })

    wx.setStorage({
      data: this.data.checked,
      key: 'checked',
    })

    wx.showToast({
      title: '保存成功',
    })

    flag = true
  },
  
  change: function(e) {
    this.setData({
      checked: !this.data.checked
    })
  },

  msg: function(e) {
    console.log('not implemented')

    if(this.data.checked) {
      wx.requestSubscribeMessage({
        tmplIds: [''],
        success(res) {
          console.log('success: ' + res)
        },
        fail: err => {
          console.log(err)
          this.setData({
            // checked: false
          })
        }
      })
    }
  }
})